import { MyVue } from "@/common/MyVue";
import { CacheKeys } from "@/constant/CacheKeys";
import Constant, { GenerateResult, TopBar } from "@/constant/Constants";
import PostInfo from "@/model/PostInfo";
import { UserInfo } from "@/model/UserInfo";
import { PostRequest } from "@/protocol/request/PostRequest";

import { UserService } from "@/service/UserService";
import DateUtil from "@/utils/DateUtil";
import LoggerUtil from "@/utils/LoggerUtil";
import UniUtil, { VideoAdOptions } from "@/utils/UniUtil";
import Util from "@/utils/Util";
import DebounceUtil from "@/utils/DebounceUtil";
import BatchDownloadUtil from "@/utils/BatchDownloadUtil";
import { onShareAppMessage } from "@dcloudio/uni-app";
import { Component, Hook, Inject, Setup, Vue } from "vue-facing-decorator";
import { PostService } from "@/service/PostService";
@Component
export default class Home extends MyVue {
    user = new UserInfo.User();
    flowList = new Array<UserInfo.SimpleUser>();
    postList = new Array<PostInfo>();
    postMap = new Map<number, PostInfo>();
    cdnHost = Constant.cdnHost;
    screenWidth: string = "";
    mediaHeight: string = "320px";
    visible: boolean = false;
    request: PostRequest.QueryList = new PostRequest.QueryList();
    observer: UniNamespace.IntersectionObserver | null = null;
    isBack: boolean = false;

    onLoad() {

        uni.setNavigationBarTitle({ title: TopBar.HOME });
        UniUtil.setStorage(CacheKeys.PROMPT, "");

        uni.getSystemInfo({
            success: (res) => {
                this.screenWidth = res.screenWidth + "px"
                this.mediaHeight = res.screenWidth * 1.25 + "px";
            }
        });

        this.init();


    }
    async load() {
        let postList = await PostService.queryRecommendList(this.request);
        Util.copyList(this.postList, postList, PostInfo);
        this.postMap.clear();
        this.postList.forEach(element => {
            this.postMap.set(element.id, element);
        });
        let followList = await UserService.queryFollowList();
        Util.copyList(this.flowList, followList, UserInfo.SimpleUser);
        this.$nextTick(() => {
            this.initIntersectionObserver();
        });
    }



    async init() {
        this.postList.length = 0;
        this.flowList.length = 0;
        this.request.pageIndex = 1;
        let user = UserService.getUser();
        if (user && user.uid > 0) {
            Util.copy(this.user, user);
        }
        this.load();
    }

    onShow(option?: any): void {
        if (this.user.uid <= 0) {
            let user = UserService.getUser();
            if (user && user.uid > 0) {
                Util.copy(this.user, user);
            }
        }
        if (!this.isBack) {
            this.init();
        }

        this.isBack = false;

    }

    changeMedia(e: any) {
        let id = e.currentTarget.dataset.id;
        let post = this.postMap.get(id);
        if (post) {
            post.postCurrent = e.detail.current;
        }
    }
    onReachBottom() {
        this.request.pageIndex += 1;
        this.load();
    }

    // 防抖版本的展开/收起标题方法
    changeShowTitle(e: any) {
        let id = e.currentTarget.dataset.id;
        let post = this.postMap.get(id);
        if (post) {
            post.hideTitle = !post.hideTitle;
        }
    }

    // 防抖版本的关注用户方法
    toFollowUser = DebounceUtil.debounce('toFollowUser', (e: any) => {
        const index = e.currentTarget.dataset.index;
        UniUtil.navigateTo("/pages/blogger/blogger?userId=" + this.flowList[index].uid);
    }, 300);

    // 防抖版本的跳转用户页面方法
    toUser(e: any) {
        this.isBack = true;
        const uid = e.currentTarget.dataset.id;
        uni.navigateTo({
            url: "/pages/blogger/blogger", success: (res) => {
                res.eventChannel.emit('toUser', { userId: uid });
            }
        });
    }
    onStopMove() { }

    onUnload() {
        if (this.observer) {
            this.observer.disconnect();
        }
    }

    generateId(itemId: any, index: any) {
        return itemId + Date.now();
    }

    initIntersectionObserver() {

    }
    truncate(str: any) {
        return Util.truncate(str, 10);
    }

    getDisplayText(text: string) {
        // let text = item.title || '';

        // // 如果content不为空，添加换行和content内容
        // if (item.content && item.content.trim()) {
        //     text += item.content.trim();
        // }
        if (Util.isEmpty(text)) {
            return;
        }
        text = text.replace(/\n\n/g, '<br/>');

        return text;
    }

    onLogin() {
        let login = UserService.checkAuth();

    }
    @Hook("onShareAppMessage")
    onShareAppMessage(e: any) {
        let login = UserService.checkAuth();
        if (!login) {
            return false;
        }

        let user = UserService.getUser();
        let uid = Util.isEmpty(user) ? 0 : user.uid;
        let post = <any>this.postMap.get(e.target.dataset.id);


        return UniUtil.onShareAppMessage(
            post.title,
            post.title,
            "/pages/blogger/post?fromUid=" + uid + "&uid=" + post.user.uid + "&postId=" + post?.id,
            this.cdnHost + post?.urls[post.postCurrent]
        );
    }

    toLogin() {
        UserService.checkAuth();
    }
    //下载当前帖子的图片
    async downPost() {
        let login = UserService.checkAuth();
        if (!login) {
            return;
        }
        let postId = this.postList[0].id; // 假设下载第一个帖子的图片
        let post = this.postMap.get(postId);
        if (Util.isEmpty(post) || !post) {
            LoggerUtil.error("post is null");
            return;
        }

        let urls = <any>[];
        (post.urls as any).forEach((url: string, index: number) => {
            // 检查URL是否已经是完整的HTTP/HTTPS地址
            if (url.startsWith('http')) {
                urls.push(url);
            } else {
                // 确保cdnHost和url之间没有重复的斜杠
                urls.push(this.cdnHost + url);
            }
        });

        if (urls && urls.length > 0) {
            // 直接保存到相册，接受系统提示
            await BatchDownloadUtil.batchDownload(urls, 3);
        } else {
            UniUtil.showError({ title: "没有可下载的图片" });
        }
    }

    //下载当前帖子的图片（带选择提示）
    async downPostWithChoice(e: any) {
        let login = UserService.checkAuth();
        if (!login) {
            return;
        }
        let id = e.currentTarget.dataset.id;
        let post = this.postMap.get(id);
        if (Util.isEmpty(post) || !post) {
            LoggerUtil.error("post is null");
            return;
        }

        let urls = <any>[];
        (post.urls as any).forEach((url: string, index: number) => {
            // 检查URL是否已经是完整的HTTP/HTTPS地址
            if (url.startsWith('http://') || url.startsWith('https://')) {
                urls.push(url);
            } else {
                // 确保cdnHost和url之间没有重复的斜杠
                const cdnHost = this.cdnHost.endsWith('/') ? this.cdnHost.slice(0, -1) : this.cdnHost;
                const cleanUrl = url.startsWith('/') ? url : '/' + url;
                urls.push(cdnHost + cleanUrl);
            }
        });

        if (urls && urls.length > 0) {
            // 让用户选择操作方式
            uni.showActionSheet({
                itemList: ['预览保存(长按图片)', '全部保存', '逐张保存'],
                success: async (res) => {
                    if (res.tapIndex === 0) {
                        // 预览图片（用户可以长按保存）
                        await BatchDownloadUtil.previewImages(urls, post.postCurrent || 0);
                    } else if (res.tapIndex === 1) {
                        // 一次性保存全部
                        await BatchDownloadUtil.batchDownload(urls, 3);
                    } else if (res.tapIndex === 2) {
                        // 逐张保存，减少弹窗频率
                        await BatchDownloadUtil.batchDownload([urls[post.postCurrent]], 1);
                    }
                }
            });
        } else {
            UniUtil.showError({ title: "没有可下载的图片" });
        }
    }

    // 防抖版本的点赞方法
    async likePost(e: any) {
        let login = UserService.checkAuth();
        if (!login) {
            return;
        }
        let postId = e.currentTarget.dataset.id;
        let post = this.postMap.get(postId);
        if (Util.isEmpty(post) || !post) {
            LoggerUtil.error("post is null");
            return;
        }

        if (post.liked) {
            await PostService.unlikePost(postId);
            post.liked = false;
            post.likeCount -= 1;
        } else {
            await PostService.likePost(postId);
            post.liked = true;
            post.likeCount += 1;
        }
    }

    // 防抖版本的收藏方法
    async collectPost(e: any) {
        let login = UserService.checkAuth();
        if (!login) {
            return;
        }
        let postId = e.currentTarget.dataset.id;
        let post = this.postMap.get(postId);
        if (Util.isEmpty(post) || !post) {
            LoggerUtil.error("post is null");
            return;
        }

        if (post.collected) {
            await PostService.uncollectPost(postId);
            post.collected = false;
        } else {
            await PostService.collectPost(postId);
            post.collected = true;
        }
    }

    formatNumber(number: number): string {
        return Util.formatNumber(number);
    }

    copyTitle(item: PostInfo) {
        let login = UserService.checkAuth();
        if (!login) {
            return;
        }
        if (!item.title && !item.content) return;

        let words = item.title + '\n' + item.content;
        // 将<br/>替换为换行符
        words = words.replace(/<br\/?>/g, '\n\n');
        uni.setClipboardData({
            data: words,
            success: () => {
                uni.showToast({ title: '已复制', icon: 'none' });
            }
        });
    }

}